import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { User, LoginCredentials, LoginResponse, Tenant, Organization } from '@/types';

// 认证状态接口
interface AuthState {
  // 状态
  user: User | null;
  currentTenant: Tenant | null;
  currentOrganization: Organization | null;
  permissions: string[];
  token: string | null;
  refreshToken: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  
  // 动作
  login: (credentials: LoginCredentials) => Promise<void>;
  logout: () => void;
  switchTenant: (tenantId: string) => Promise<void>;
  switchOrganization: (organizationId: string) => Promise<void>;
  updateProfile: (profile: Partial<User>) => Promise<void>;
  refreshTokens: () => Promise<void>;
  setLoading: (loading: boolean) => void;
  checkAuth: () => Promise<boolean>;
  hasPermission: (permission: string) => boolean;
  hasRole: (role: string) => boolean;
  hasAnyPermission: (permissions: string[]) => boolean;
  hasAllPermissions: (permissions: string[]) => boolean;
}

// 认证状态存储
export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      // 初始状态
      user: null,
      currentTenant: null,
      currentOrganization: null,
      permissions: [],
      token: null,
      refreshToken: null,
      isAuthenticated: false,
      isLoading: false,

      // 登录
      login: async (credentials: LoginCredentials) => {
        set({ isLoading: true });
        try {
          // 这里将调用API服务
          const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(credentials),
          });

          if (!response.ok) {
            throw new Error('登录失败');
          }

          const data: LoginResponse = await response.json();
          
          set({
            user: data.user,
            currentTenant: data.currentTenant,
            currentOrganization: data.currentOrganization,
            permissions: data.permissions,
            token: data.token,
            refreshToken: data.refreshToken,
            isAuthenticated: true,
            isLoading: false,
          });

          // 设置请求头
          if (data.token) {
            localStorage.setItem('auth_token', data.token);
          }
        } catch (error) {
          set({ isLoading: false });
          throw error;
        }
      },

      // 登出
      logout: () => {
        localStorage.removeItem('auth_token');
        set({
          user: null,
          currentTenant: null,
          currentOrganization: null,
          permissions: [],
          token: null,
          refreshToken: null,
          isAuthenticated: false,
          isLoading: false,
        });
      },

      // 切换租户
      switchTenant: async (tenantId: string) => {
        set({ isLoading: true });
        try {
          const response = await fetch('/api/auth/switch-tenant', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${get().token}`,
            },
            body: JSON.stringify({ tenantId }),
          });

          if (!response.ok) {
            throw new Error('切换租户失败');
          }

          const data = await response.json();
          
          set({
            currentTenant: data.currentTenant,
            currentOrganization: data.currentOrganization,
            permissions: data.permissions,
            isLoading: false,
          });
        } catch (error) {
          set({ isLoading: false });
          throw error;
        }
      },

      // 切换组织
      switchOrganization: async (organizationId: string) => {
        set({ isLoading: true });
        try {
          const response = await fetch('/api/auth/switch-organization', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${get().token}`,
            },
            body: JSON.stringify({ organizationId }),
          });

          if (!response.ok) {
            throw new Error('切换组织失败');
          }

          const data = await response.json();
          
          set({
            currentOrganization: data.currentOrganization,
            permissions: data.permissions,
            isLoading: false,
          });
        } catch (error) {
          set({ isLoading: false });
          throw error;
        }
      },

      // 更新用户资料
      updateProfile: async (profile: Partial<User>) => {
        const { user } = get();
        if (!user) return;

        set({ isLoading: true });
        try {
          const response = await fetch(`/api/users/${user.id}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${get().token}`,
            },
            body: JSON.stringify(profile),
          });

          if (!response.ok) {
            throw new Error('更新用户资料失败');
          }

          const updatedUser = await response.json();
          
          set({
            user: updatedUser,
            isLoading: false,
          });
        } catch (error) {
          set({ isLoading: false });
          throw error;
        }
      },

      // 刷新令牌
      refreshTokens: async () => {
        const { refreshToken } = get();
        if (!refreshToken) {
          get().logout();
          return;
        }

        try {
          const response = await fetch('/api/auth/refresh', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ refreshToken }),
          });

          if (!response.ok) {
            get().logout();
            return;
          }

          const data = await response.json();
          
          set({
            token: data.token,
            refreshToken: data.refreshToken,
          });

          localStorage.setItem('auth_token', data.token);
        } catch (error) {
          get().logout();
        }
      },

      // 设置加载状态
      setLoading: (loading: boolean) => {
        set({ isLoading: loading });
      },

      // 检查认证状态
      checkAuth: async (): Promise<boolean> => {
        const token = localStorage.getItem('auth_token');
        if (!token) {
          set({ isAuthenticated: false });
          return false;
        }

        try {
          // 在开发环境中，简化认证检查逻辑
          if (import.meta.env.DEV) {
            // 假设 token 有效，使用模拟数据
            set({
              isAuthenticated: true,
              token,
            });
            return true;
          }
          
          const response = await fetch('/api/auth/me', {
            headers: {
              'Authorization': `Bearer ${token}`,
            },
          });

          if (!response.ok) {
            get().logout();
            return false;
          }

          const data = await response.json();
          
          set({
            user: data.user,
            currentTenant: data.currentTenant,
            currentOrganization: data.currentOrganization,
            permissions: data.permissions,
            token,
            isAuthenticated: true,
          });

          return true;
        } catch (error) {
          get().logout();
          return false;
        }
      },

      // 检查权限
      hasPermission: (permission: string): boolean => {
        const { permissions } = get();
        return permissions.includes(permission);
      },

      // 检查角色
      hasRole: (role: string): boolean => {
        const { user } = get();
        return user?.roles.includes(role) || false;
      },

      // 检查是否有任一权限
      hasAnyPermission: (permissions: string[]): boolean => {
        const { permissions: userPermissions } = get();
        return permissions.some(permission => userPermissions.includes(permission));
      },

      // 检查是否有所有权限
      hasAllPermissions: (permissions: string[]): boolean => {
        const { permissions: userPermissions } = get();
        return permissions.every(permission => userPermissions.includes(permission));
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        currentTenant: state.currentTenant,
        currentOrganization: state.currentOrganization,
        permissions: state.permissions,
        token: state.token,
        refreshToken: state.refreshToken,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);

// 认证钩子
export const useAuth = () => {
  const auth = useAuthStore();
  
  return {
    ...auth,
    isAdmin: auth.hasRole('admin'),
    isSuperAdmin: auth.hasRole('super_admin'),
    canManageTenants: auth.hasPermission('tenant.manage'),
    canManageUsers: auth.hasPermission('user.manage'),
    canManageOrganizations: auth.hasPermission('organization.manage'),
    canViewDashboard: auth.hasPermission('dashboard.view'),
  };
};